package com.yinshu.teleshield.config;

import cn.hutool.core.util.StrUtil;
import com.yinshu.teleshield.tkbase.base.R;
import com.yinshu.teleshield.tkbase.exception.VerifyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 异常处理器
 **/
@RestControllerAdvice
public class ExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        logger.error(e.getMessage(), e);
        if (e instanceof HttpRequestMethodNotSupportedException) {
            return R.fail("请求方式错误");
        }
        return R.fail(e.getMessage());
    }

    /**
     * 处理自定义校验异常
     */
    @org.springframework.web.bind.annotation.ExceptionHandler({VerifyException.class, MethodArgumentNotValidException.class})
    public R handleVerifyException(Exception e) {
        logger.error(e.getMessage(), e);
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException e1 = (MethodArgumentNotValidException) e;
            return R.fail(StrUtil.split((String) e1.getDetailMessageArguments()[1], ":").get(1).trim());
        } else {
            return R.fail(e.getMessage());
        }
    }

}
